<?php

namespace addon\ly_shareholder\app\job;

use addon\ly_shareholder\app\model\ShareholderLog;
use addon\ly_shareholder\app\service\core\CoreConfigService;
use addon\ly_shareholder\app\service\core\CoreShareholderDividendService;
use addon\ly_shareholder\app\service\core\CoreShareholderSendService;
use addon\shop\app\dict\order\OrderDict;
use addon\shop\app\model\order\Order;
use app\model\site\Site;
use core\base\BaseJob;
use think\facade\Log;

/**
 * 股东结算发放任务
 */
class ShareholderSettlement extends BaseJob
{
    /**
     * 消费
     * @return true
     */
    public function doJob()
    {
        //执行股东分红
        $site_list = (new Site())->column('site_id');

        foreach($site_list as $site_id){
            try{
                $config = (new CoreConfigService())->getShareholderConfig($site_id);

                if(!$config || $config['is_open'] == 0) continue;

                $order = (new Order())->where([
                    ['site_id', '=', $site_id],
                    ['status', 'in', [OrderDict::WAIT_DELIVERY, OrderDict::WAIT_PAY, OrderDict::FINISH]],
                ])->findOrEmpty();

                if(!$order->isEmpty()){
                    Log::write('======昨日有订单进入分红执行' . '订单站点ID：' . $order['site_id'] . '=========');
                    (new CoreShareholderDividendService($order['site_id']))->handleQueue($order['site_id']);
                    
                }else{
                    Log::write('======昨日无订单进入分红执行======ly_shareholder===========');
                    continue;
                }
            }catch(\Exception $e){
                Log::write('站点ID：' . $site_id . ' 分红处理异常：' . $e->getMessage());
                continue;
            }
        }




        // 查询所有未结算的股东分红
        try {
            $list = (new ShareholderLog())->where([['is_settlement', '=', 0]])->select();
            if(!$list->isEmpty()){
                $core_shareholder_send = new CoreShareholderSendService();
                foreach($list as $v){
                    $core_shareholder_send->autoSettlement($v);
                }
            }
            Log::write('股东结算发放任务执行成功');
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

}
